package com.hksj.Intelligentmanagement.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hksj.Intelligentmanagement.dto.AurgicalAssistantRelationDTO;
import com.hksj.Intelligentmanagement.dto.OperatingRoomInfoAndSurgicalAssistantDTO;
import com.hksj.Intelligentmanagement.dto.OperatingRoomInfoDTO;
import com.hksj.Intelligentmanagement.entity.AurgicalAssistantRelationEntity;
import com.hksj.Intelligentmanagement.entity.OperatingRoomInfoEntity;
import com.hksj.Intelligentmanagement.mapper.OperatingRoomInfoMapper;
import com.hksj.Intelligentmanagement.mapper.SurgicalAssistantRelationMapper;
import com.hksj.Intelligentmanagement.mapper.SurgicalInfoMapper;
import com.hksj.Intelligentmanagement.vo.AurgicalAssistantRelationEntityVo;
import com.hksj.Intelligentmanagement.vo.OperatingRoomInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @ClassName OperatingRoomInfoService
 * @Description TODO
 * @Author @陈章
 * @Date 2023/3/31 16:12
 * @Version 1.0
 */
@Service
public class OperatingRoomInfoService extends ServiceImpl<OperatingRoomInfoMapper, OperatingRoomInfoEntity> {
    @Autowired
    private OperatingRoomInfoMapper mapper;

    @Autowired
    private SurgicalAssistantRelationMapper surgicalAssistantRelationMapper;

    @Autowired
    private SurgicalInfoMapper surgicalInfoMapper;

    public void addOperatingRoomInfo(OperatingRoomInfoDTO operatingRoomInfoDTO) {
        OperatingRoomInfoEntity operatingRoomInfoEntity = new OperatingRoomInfoEntity();
        BeanUtils.copyProperties(operatingRoomInfoDTO, operatingRoomInfoEntity);
        int insert = mapper.insert(operatingRoomInfoEntity);
        if (insert <= 0) {
            throw new RuntimeException("新增失败");
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addOperatingRoomInfoAndSurgicalAssistant(List<OperatingRoomInfoAndSurgicalAssistantDTO> dto) {
        //检验是否存在重复排班
        boolean hasDuplicates = dto.stream()
                .map(OperatingRoomInfoAndSurgicalAssistantDTO::getSurgicalInfoId)  // 使用对象的getId方法来映射id
                .distinct()  // 过滤掉重复的id
                .count() != dto.size();
        if (hasDuplicates) {
            throw new RuntimeException("手术信息存在重复排期");
        }

        for (OperatingRoomInfoAndSurgicalAssistantDTO operatingRoomInfoAndSurgicalAssistantDTO : dto) {
            //新增手术间和手术的信息
            OperatingRoomInfoEntity operatingRoomInfoEntity = new OperatingRoomInfoEntity();
            BeanUtils.copyProperties(operatingRoomInfoAndSurgicalAssistantDTO, operatingRoomInfoEntity);
            if (StringUtils.isEmpty(operatingRoomInfoEntity.getId())) {
                mapper.insert(operatingRoomInfoEntity);
            } else {
                mapper.updateById(operatingRoomInfoEntity);
            }
            //取出所有所有的麻醉师
            List<AurgicalAssistantRelationDTO> list = operatingRoomInfoAndSurgicalAssistantDTO.getList();
            //检验是否存在重复排班
//            boolean b = list.stream()
//                    .map(AurgicalAssistantRelationDTO::getId)  // 使用对象的getId方法来映射id
//                    .distinct()  // 过滤掉重复的id
//                    .count() != dto.size();
//            if (b) {
//                throw new RuntimeException("手术信息为" + operatingRoomInfoAndSurgicalAssistantDTO.getSurgicalInfo() + "的麻醉师不能重复");
//            }

            List<AurgicalAssistantRelationEntity> entityList = JSONObject.parseArray(JSONObject.toJSONString(list), AurgicalAssistantRelationEntity.class);
            entityList.forEach(entity -> entity.setSurgicalInfoId(operatingRoomInfoAndSurgicalAssistantDTO.getSurgicalInfoId()));
            entityList.forEach(entity -> {
                if (entity.getId() == null || entity.getId().isEmpty()) {
                    // 如果id为空，则设置为32位UUID
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    entity.setId(uuid);
                }
            });
            int i = surgicalAssistantRelationMapper.saveOrUpdateBatch(entityList);

            if (i <= 0) {
                throw new RuntimeException("新增失败");
            }
            //提交排班改变排班状态
            surgicalInfoMapper.updateStatusById(operatingRoomInfoAndSurgicalAssistantDTO.getSurgicalInfoId(), 1);
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void delOperatingRoomInfoAndSurgicalAssistant(String surgicalInfoId) {

        QueryWrapper<OperatingRoomInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("surgical_info_id", surgicalInfoId);
        int delete = mapper.delete(wrapper);

        QueryWrapper<AurgicalAssistantRelationEntity> wrapper1 = new QueryWrapper<>();
        wrapper.eq("surgical_info_id", surgicalInfoId);
        int delete1 = surgicalAssistantRelationMapper.delete(wrapper1);
        if (delete <= 0 || delete1 <= 0) {
            throw new RuntimeException("删除失败");
        }
        //提交排班改变排班状态
        surgicalInfoMapper.updateStatusById(surgicalInfoId, 0);
    }

    public List<OperatingRoomInfoVo> selectAllOperatingRoomInfoAndSurgicalAssistant(String time,String name) {

        List<OperatingRoomInfoVo> OperatingRoomInfoList = mapper.selectOperatingRoomInfo(time,name);
        if (CollectionUtils.isEmpty(OperatingRoomInfoList)) {
            return new ArrayList<OperatingRoomInfoVo>();
        }
        List<AurgicalAssistantRelationEntityVo> surgicalAssistantRelationList = surgicalAssistantRelationMapper.surgicalAssistantRelation(time);
        for (OperatingRoomInfoVo operatingRoomInfoVo : OperatingRoomInfoList) {
            // 使用Stream API过滤具有特定ID的对象
            List<AurgicalAssistantRelationEntityVo> filteredList = surgicalAssistantRelationList.stream()
                    .filter(obj -> obj.getSurgicalInfoId().equals(operatingRoomInfoVo.getSurgicalInfoId()))
                    .collect(Collectors.toList());
            operatingRoomInfoVo.setList(filteredList);
        }
        return OperatingRoomInfoList;
    }
}
